import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 轨道控制
import { GUI } from 'lil-gui';

const params = {
  color: '0xfff000',
};
export default function index() {
  const mountRef = useRef(null);
  const gui = new GUI();
  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75);
    camera.position.z = 5;
    camera.position.x = 1;
    camera.position.y = 1;
    scene.add(camera);

    const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    const boxMeterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
    const boxMesh = new THREE.Mesh(boxGeometry, boxMeterial);
    scene.add(boxMesh);

    // gui  gui.add(对象，‘对象的属性’)
    gui.add(boxMesh, 'visible');
    gui.add(boxMesh.position, 'x').min(-3).max(3).step(0.1);
    gui.addColor(params, 'color').onChange(() => {
      boxMeterial.color.set(params.color);
    });
    gui.add(boxMeterial, 'wireframe');

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement); // 将渲染器的DOM元素添加到React组件
    renderer.render(scene, camera);

    // 轨道控制
    const controls = new OrbitControls(camera, renderer.domElement);

    const animate = () => {
      controls.update();
      renderer.render(scene, camera);
      window.requestAnimationFrame(animate); // 会在下一帧调用此函数
    };
    animate();
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%', height: '100vh' }}
    />
  );
}
